import React, { Component } from 'react';
import './Login.css';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import {loginProcessing} from '../../action';

import { Form, Icon, Input, Button, Checkbox, Alert} from 'antd';
const FormItem = Form.Item;

class NormalLoginForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      redirectToReferrer: false
    };
  }
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        // 验证登陆
        this.props.submitLoginForm(values);
      }
    });
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { from } = this.props.location.state || { from: { pathname: '/app/dashboard' } }
    // 登陆成功自动跳转
    if (this.props.authenticated) {
     
      console.log("redirectToReferrer:", this.props.authenticated)
      return (
        <Redirect to={from} />
      )
    }
    return (
       <div className="form" id="components-form-login">
            <Form onSubmit={this.handleSubmit} className="login-form" >
            <FormItem>
                {getFieldDecorator('userName', {
                rules: [{ required: true, message: '请输入你的用户名!' }],
                })(
                <Input prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder="Username" />
                )}
            </FormItem>
            <FormItem>
                {getFieldDecorator('password', {
                rules: [{ required: true, message: '请输入你的密码!' }],
                })(
                <Input prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder="Password" />
                )}
            </FormItem>
            <FormItem>
                {getFieldDecorator('remember', {
                valuePropName: 'checked',
                initialValue: true,
                })(
                <Checkbox>Remember me</Checkbox>
                )}
                {/* <a className="login-form-forgot" href="">Forgot password</a> */}
                <Button type="primary" htmlType="submit" className="login-form-button">
                Log in
                </Button>
                Or <a href="">Forgot password </a>
            </FormItem>
            </Form>
            {this.props.errorMessage ? (
            <Alert message={this.props.errorMessage} type="error" showIcon />) : ''
            }
        </div>
    );
  }
}

const Login = Form.create()(NormalLoginForm);
// map属性
const mapStateToProps = (state) => {
  return {
    authenticated: state.auth.authenticated,
    errorMessage: state.auth.error
  }
}
// map 函数
const mapDispatchToProps = (dispatch) => {
  return {
      submitLoginForm: (values) => {
          dispatch(loginProcessing(values))
      }
  }
}


export default connect(mapStateToProps, mapDispatchToProps)(Login);